﻿using LogLib;
using System;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Reflection;
using ComLib.ConfigService;
using ComLib;
using KAImage.Config;

namespace KAImage
{
    /// <summary>
    /// 配置文件管理类
    /// </summary>
    public static class ConfigFiles
    {
        /// <summary>
        /// 错误信息
        /// </summary>
        private static string _errorMessage;
        public static string ErrorMessage
        {
            get { return _errorMessage; }
        }

        private static ConfigService _service;
        public static ConfigService Service
        {
            get { return _service; }
        }

        public static void Initialize()
        {
            InitConfigData();
            CheckFolder();               
        }

        public static void InitConfigData()
        {
            _errorMessage = "";
            try
            {
                _service = ConfigService.GetInstance();
                _service.LoadConfig();
            }
            catch (Exception ex)
            {
                _errorMessage = ex.Message;
                Log.WriteException(ex.ToString());
            }
        }

        delegate void CheckDelegate(string s);
        public static void CheckFolder()
        {
            CheckDelegate delFun = (string path) =>
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            };
            string configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6) + "\\Config";
            delFun(configDirectory);
        }
     
        /// <summary>
        /// 保存设置
        /// </summary>
        public static bool SaveSettings()
        {
            _errorMessage = "";
            try
            {              
                _service.SaveConfig();
                return true;
            }
            catch (System.Exception ex)
            {
                Log.WriteException(ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 导出设置
        /// </summary>
        public static bool ExportSettings(string folder)
        {
            _errorMessage = "";
            if (_service.ExportConfig(folder))
            {
                Log.WriteAsync("导出方案配置成功");
                return true;
            }
            else
            {
                Log.WriteAsync("导出方案配置失败:" + _service.Error);
                _errorMessage = _service.Error;
                return false;
            }
        }
    };
}
